package com.ksyun.campus.dataserver.util;

import org.springframework.util.FileSystemUtils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class FileUtil {
    /**
     * 将byte数组写入本地文件
     *
     * @param data     byte数组
     * @param fileName 文件名
     * @throws IOException
     */
    public static void writeByteArrayToFile(byte[] data, String fileName) throws IOException {
        try (BufferedOutputStream bos = new BufferedOutputStream(Files.newOutputStream(Paths.get(fileName)))) {
            bos.write(data);
            System.out.println("Byte array written to file: " + fileName);
        }
    }

    public static String getIdFromByteArray(byte[] byteArray) {
        try {
            // 将byte[]数组内容进行哈希计算，生成唯一的id
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] hash = md.digest(byteArray);

            // 将哈希值转化为字符串格式的id
            ByteBuffer buffer = ByteBuffer.wrap(hash);
            long high = buffer.getLong();
            long low = buffer.getLong();
            return Long.toHexString(high) + Long.toHexString(low);
        } catch (NoSuchAlgorithmException e) {
            // 如果指定的哈希算法不存在，则抛出异常
            throw new RuntimeException("Could not initialize MessageDigest", e);
        }
    }

    public static void deleteFile(String fileName) {
        FileSystemUtils.deleteRecursively(new File(fileName));
    }
}
